package com.example.demo.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import lombok.extern.log4j.Log4j2;

/**
 *  自定义过滤器，ajax请求数据 以json格式返回
 * Created by lihui on 2019/2/28.
 */
@Log4j2
public class ShiroSimpleAuthenticationFilter extends FormAuthenticationFilter {

	@Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpRequest = (HttpServletRequest)request; 		 
		if (isAjaxRequest(httpRequest)) {			
			if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } 
			else {
			    HttpServletResponse httpServletResponse = (HttpServletResponse)response;
	            httpServletResponse.sendError(401);
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                //allow them to see the login page ;)
                return true;
            }
        }		 
		return super.onAccessDenied(request,response);
    }
 
    /*
     * 判断 是否为Ajax 请求
     * @param request
     * @return
     */
    boolean isAjaxRequest(HttpServletRequest request){    	
    	return (request.getHeader("x-requested-with") != null    
    		    && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest"));
    }
	
}
